package com.zqh.apiindeximgquery.sentinel;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.fastjson.JSON;
import com.zqh.myfmmall.result.Result;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description : 对前端请求的那些接口资源中sentinel抛出异常时进行友好响应
 * @Author :kono淇杭哒、
 * @Create 2022-03-17 17:47
 */
@Component
public class SentinelExceptionHandler implements BlockExceptionHandler{
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        Result result = Result.internalServerError();
        if (e instanceof FlowException) {
            result.setMessage("请求被限流了");
        } else if (e instanceof ParamFlowException) {
            result.setMessage("请求被热点参数限流");
        } else if (e instanceof DegradeException) {
            result.setMessage("请求被降级了");
        } else if (e instanceof AuthorityException) {
            result.setMessage("没有权限访问");
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(JSON.toJSONString(result));
    }
}